package com.example.news.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.news.mapper.UserMapper;
import com.example.news.mapper.UserRoleMapper;
import com.example.news.pojo.entity.User;
import com.example.news.pojo.entity.UserRole;
import com.example.news.pojo.form.AddUserRoleForm;
import com.example.news.pojo.form.ChangeUserInfoForm;
import com.example.news.pojo.form.RegisterForm;
import com.example.news.pojo.form.UserPageQuery;
import com.example.news.pojo.vo.UserInfoVo;
import com.example.news.service.UserService;
import com.example.news.utils.JwtHelper;
import com.example.news.utils.MD5Util;
import com.example.news.utils.result.PageResult;
import com.example.news.utils.result.Result;
import com.example.news.utils.result.ResultCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private JwtHelper jwtHelper;

    public Result<UserInfoVo> getMineInfo(String token) {
        //获取token对应的用户
        int userId = jwtHelper.getUserId(token).intValue();
        //查询数据
        User user = userMapper.selectById(userId);

        if (user != null) {
            user.setPassword(null);
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(user, userInfoVo);
            return Result.ok(userInfoVo);
        }

        return Result.build(null, ResultCodeEnum.NOTLOGIN);
    }

    @Override
    public Result<String> addUser(RegisterForm registerForm) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, registerForm.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        User user1 = new User();
        BeanUtils.copyProperties(registerForm, user1);
        //对密码进行加密
        user1.setPassword(MD5Util.encrypt(registerForm.getPassword()));
        this.save(user1);
        return Result.ok(null, "成功添加新用户！");
    }

    @Override
    public Result<UserInfoVo> getOtherInfo(Integer id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            user.setPassword(null);
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(user, userInfoVo);
            return Result.ok(userInfoVo);
        }
        return Result.build(null, ResultCodeEnum.USER_ERROR);

    }

    @Override
    public PageResult<UserInfoVo> getUserInfoList(UserPageQuery userPageQuery) {
        Page<User> userPage = new Page<>(userPageQuery.getPageNum(), userPageQuery.getPageSize());
        IPage<UserInfoVo> convertPage = userMapper.getUserPage(userPage, userPageQuery);
        return PageResult.success(convertPage);
    }

    @Override
    public Result<String> updateUserInfo(ChangeUserInfoForm changeUserInfoForm) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, changeUserInfoForm.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            BeanUtils.copyProperties(changeUserInfoForm, user);
            if (this.updateById(user)) {
                return Result.ok(null, "资料修改成功！");
            } else {
                return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
            }
        }
        return Result.build(null, ResultCodeEnum.USER_ERROR);
    }

    @Override
    public Result<String> updateUserStatus(Integer id, Integer status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, user.getId())
                    .set(User::getStatus, status);
            if (this.update(updateWrapper)) {
                return Result.ok(null, "修改成功！");
            } else {
                return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
            }
        }
        return Result.build(null, ResultCodeEnum.USER_ERROR);
    }

    @Override
    public Result<String> deleteUser(Integer id) {
        //查询数据
        User user = userMapper.selectById(id);
        if (user != null) {
            userMapper.deleteById(user.getId());
            return Result.ok(null, "注销成功！");
        }
        return Result.build(null, ResultCodeEnum.USER_ERROR);
    }

    @Override
    public Result<String> deleteMine(String token) {
        //获取token对应的用户
        int userId = jwtHelper.getUserId(token).intValue();
        //查询数据
        User user = userMapper.selectById(userId);
        if (user != null) {
            userMapper.deleteById(user.getId());
            return Result.ok(null, "注销成功！");
        }
        return Result.build(null, ResultCodeEnum.USER_ERROR);
    }

    @Override
    public Result<String> addUserRole(AddUserRoleForm addUserRoleForm) {
        try {
            for (Long roleId : addUserRoleForm.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(addUserRoleForm.getUserId());
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
            return Result.ok(null, "添加成功！");
        } catch (Exception e) {
            return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
        }
    }
}
